import {
  Button,
  Col,
  Drawer,
  Form,
  Input,
  message,
  Radio,
  Row,
  Upload,
} from "antd";
import { useForm } from "antd/lib/form/Form";
import TextArea from "antd/lib/input/TextArea";
import { RcFile } from "antd/lib/upload";
import { UploadFile } from "antd/lib/upload/interface";
import { useCallback, useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { AddContent, UpdateContent } from "http/content-http";
import { apiUrl } from "http/http";
import {
  editActions,
  selectIsShowEditModal,
  selectEditContent,
  contentObj,
} from "./edit.slice";
import { useCloseEditModal } from "./util";

export const EditModalScreen = () => {
  const dispatch = useDispatch();
  const closeEditModal = useCloseEditModal();
  const isVisible = useSelector(selectIsShowEditModal);
  const [form] = useForm();

  const content = useSelector(selectEditContent) as contentObj | undefined;

  const [title, setTitle] = useState("");
  useEffect(() => {
    setTitle(!!content ? "编辑项目" : "创建项目");
    form.setFieldsValue({
      ...content,
      imgUrl: content
        ? [
            {
              uid: content.id,
              name: content.imgUrl,
              status: "done",
              response: {
                data: {
                  filePath: content.imgUrl,
                },
              },
            },
          ]
        : [],
      fileUrl: content
        ? [
            {
              uid: content.id,
              name: content.fileUrl,
              status: "done",
              response: {
                data: {
                  filePath: content.fileUrl,
                },
              },
            },
          ]
        : [],
    });
  }, [content, form, setTitle]);

  const onClose = useCallback(() => {
    form.resetFields();
    closeEditModal();
  }, [closeEditModal, form]);

  const fileBeforeUpload = useCallback((file: RcFile) => {
    const type = !!~file.name.indexOf(".md");
    if (!type) {
      message.error("此项目仅支持markdown文件");
    }
    const isLt10M = file.size / 1024 / 1024 < 10;
    if (!isLt10M) {
      message.error("文件最大10MB!");
    }
    return type;
  }, []);

  const imgBeforeUpload = useCallback((file: RcFile) => {
    const type = file.type === "image/png" || file.type === "image/jpeg";
    if (!type) {
      message.error("此项目仅支持png/jpeg");
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error("文件最大2MB!");
    }
    return type;
  }, []);

  const handleSubmit = useCallback(
    ({
      title,
      author,
      original,
      tag,
      imgUrl,
      fileUrl,
      tip,
      isnote,
      demoUrl,
    }: {
      title: string;
      author: string;
      original: string;
      tag: string;
      imgUrl: UploadFile | UploadFile[];
      fileUrl: UploadFile | UploadFile[];
      tip: string;
      isnote: string;
      demoUrl: string;
    }) => {
      const img: UploadFile = (imgUrl as UploadFile[]).length
        ? (imgUrl as UploadFile[])[0]
        : (imgUrl as UploadFile);
      const file: UploadFile = (fileUrl as UploadFile[]).length
        ? (fileUrl as UploadFile[])[0]
        : (fileUrl as UploadFile);

      if (!content) {
        AddContent({
          title,
          author,
          original,
          tag,
          imgUrl: img.response.data.filePath,
          fileUrl: file.response ? file.response.data.filePath : "",
          tip,
          isnote,
          demoUrl,
        })
          .then((content) => {
            dispatch(editActions.setContent(content));
            message.success("内容添加成功!");
          })
          .catch((error) => {
            dispatch(editActions.setContent([]));
            message.error(`内容添加失败! ${error}`);
          });
      } else {
        UpdateContent({
          id: content?.id,
          title,
          author,
          original,
          tag,
          imgUrl: img.response.data.filePath,
          fileUrl:  file.response ? file.response.data.filePath : "",
          tip,
          isnote,
          demoUrl,
        })
          .then((content) => {
            dispatch(editActions.updateContent(content[0]));
            message.success("内容更新成功!");
          })
          .catch((error) => {
            dispatch(editActions.setContent([]));
            message.error(`内容更新失败! ${error}`);
          });
      }
      onClose();
    },
    [dispatch, content, onClose]
  );

  return (
    <Drawer
      forceRender={true}
      visible={isVisible}
      getContainer={false}
      onClose={onClose}
      width={"100%"}
    >
      <h1>{title}</h1>

      <Form form={form} layout={"vertical"} onFinish={handleSubmit}>
        <Row>
          <Col span={10}>
            <Form.Item
              label="标题"
              name={"title"}
              rules={[{ required: true, message: "请输入标题" }]}
            >
              <Input placeholder={"请输入标题"} />
            </Form.Item>
          </Col>

          <Col span={10} offset={2}>
            <Form.Item
              label="作者"
              name={"author"}
              rules={[{ required: true, message: "请输入作者" }]}
            >
              <Input placeholder={"请输入作者"} />
            </Form.Item>
          </Col>
        </Row>
        <Row>
          <Col span={10}>
            <Form.Item label="是否原创" name={"original"}>
              <Radio.Group buttonStyle="solid">
                <Radio.Button value={1}>原创</Radio.Button>
                <Radio.Button value={0}>借鉴总结</Radio.Button>
              </Radio.Group>
            </Form.Item>
          </Col>

          <Col span={10} offset={2}>
            <Form.Item
              label="标签"
              name={"tag"}
              rules={[{ required: true, message: "请输入标签" }]}
            >
              <Input placeholder={"请输入标签"} />
            </Form.Item>
          </Col>
        </Row>
        <Row>
          <Col span={10}>
            <Form.Item
              label="是否是笔记文章"
              name={"isnote"}
              rules={[{ required: true, message: "请选择内容类型" }]}
            >
              <Radio.Group buttonStyle="solid">
                <Radio.Button value={0}>Demo</Radio.Button>
                <Radio.Button value={1}>笔记文章</Radio.Button>
              </Radio.Group>
            </Form.Item>
          </Col>
          <Col span={10} offset={2}>
            <Form.Item label="Demo链接" name={"demoUrl"}>
              <Input placeholder={"请输入Demo链接"} />
            </Form.Item>
          </Col>
        </Row>
        <Row>
          <Col span={10}>
            <Form.Item
              label="请上传头图"
              name={"imgUrl"}
              rules={[{ required: true, message: "请上传头图" }]}
              valuePropName="fileList"
              getValueFromEvent={(e) => {
                if (Array.isArray(e)) {
                  return e;
                }
                return e && e.fileList;
              }}
            >
              <Upload
                action={`${apiUrl}/UploadContentImg`}
                beforeUpload={imgBeforeUpload}
                maxCount={1}
              >
                <Button>请上传头图</Button>
              </Upload>
            </Form.Item>
          </Col>
          <Col span={10} offset={2}>
            <Form.Item
              label="请上传内容文件"
              name={"fileUrl"}
              valuePropName="fileList"
              getValueFromEvent={(e) => {
                if (Array.isArray(e)) {
                  return e;
                }
                return e && e.fileList;
              }}
            >
              <Upload
                action={`${apiUrl}/UploadContentMD`}
                beforeUpload={fileBeforeUpload}
                maxCount={1}
              >
                <Button>请上传内容文件</Button>
              </Upload>
            </Form.Item>
          </Col>
        </Row>

        <Row>
          <Col span={22}>
            <Form.Item
              label="简介"
              name={"tip"}
              rules={[{ required: true, message: "请输入简介" }]}
            >
              <TextArea autoSize placeholder={"请输入简介"} />
            </Form.Item>
          </Col>
        </Row>
        <Form.Item>
          <Button type={"primary"} htmlType={"submit"}>
            {"完成"}
          </Button>
        </Form.Item>
      </Form>
    </Drawer>
  );
};
